document.addEventListener('DOMContentLoaded', function() {
    // DOM 元素
    const statusIndicator = document.getElementById('statusIndicator');
    const statusText = document.getElementById('statusText');
    const engineConfig = document.getElementById('engineConfig');
    const targetLangConfig = document.getElementById('targetLangConfig');
    const configStatus = document.getElementById('configStatus');
    const translateBtn = document.getElementById('translateBtn');
    const translateBtnText = document.getElementById('translateBtnText');
    const settingsBtn = document.getElementById('settingsBtn');

    // 初始化
    init();

    async function init() {
        try {
            await checkPageSupport();
            await loadConfiguration();
            setupEventListeners();
        } catch (error) {
            console.error('Popup initialization error:', error);
            showError('初始化失败，请刷新页面重试');
        }
    }

    // 检查当前页面是否支持
    async function checkPageSupport() {
        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

        if (!tab || !tab.url) {
            showUnsupported('无法获取当前页面信息');
            return;
        }

        const url = tab.url;
        const supportedSites = [
            'codeforces.com/problemset/problem/',
            'codeforces.com/contest/',
            'atcoder.jp/contests/',
            'atcoder.jp/tasks/'
        ];

        const isSupported = supportedSites.some(site => url.includes(site));

        if (isSupported) {
            showSupported('当前页面支持翻译');
            translateBtn.disabled = false;
        } else {
            showUnsupported('当前页面不支持翻译');
            translateBtn.disabled = true;
        }
    }

    // 显示支持状态
    function showSupported(message) {
        statusIndicator.className = 'status-indicator status-supported';
        statusText.textContent = message;
    }

    // 显示不支持状态
    function showUnsupported(message) {
        statusIndicator.className = 'status-indicator status-unsupported';
        statusText.textContent = message;
    }

    // 显示错误状态
    function showError(message) {
        statusIndicator.className = 'status-indicator status-unsupported';
        statusText.textContent = message;
    }

    // 加载配置信息
    async function loadConfiguration() {
        try {
            const config = await chrome.storage.sync.get({
                translationEngine: 'openai',
                targetLanguage: 'zh-CN',
                openaiApiKey: '',
                youdaoApiKey: '',
                youdaoAppSecret: ''
            });

            // 显示引擎配置
            const engineNames = {
                'openai': 'OpenAI',
                'youdao': '有道翻译'
            };
            engineConfig.textContent = engineNames[config.translationEngine] || '未知';

            // 显示目标语言
            const languageNames = {
                'zh-CN': '简体中文',
                'zh-TW': '繁体中文',
                'en': 'English'
            };
            targetLangConfig.textContent = languageNames[config.targetLanguage] || '未知';

            // 检查配置完整性
            const isConfigured = checkConfiguration(config);
            configStatus.textContent = isConfigured ? '✅ 已配置' : '⚠️ 需要配置';
            configStatus.style.color = isConfigured ? '#28a745' : '#ffc107';

        } catch (error) {
            console.error('Failed to load configuration:', error);
            configStatus.textContent = '❌ 配置错误';
            configStatus.style.color = '#dc3545';
        }
    }

    // 检查配置是否完整
    function checkConfiguration(config) {
        if (config.translationEngine === 'openai') {
            return config.openaiApiKey && config.openaiApiKey.trim() !== '';
        } else if (config.translationEngine === 'youdao') {
            return config.youdaoApiKey && config.youdaoApiKey.trim() !== '' &&
                   config.youdaoAppSecret && config.youdaoAppSecret.trim() !== '';
        }
        return false;
    }

    // 设置事件监听器
    function setupEventListeners() {
        // 翻译按钮点击事件
        translateBtn.addEventListener('click', handleTranslate);

        // 设置按钮点击事件
        settingsBtn.addEventListener('click', openSettings);

        // 监听来自content script的消息
        chrome.runtime.onMessage.addListener(handleMessage);
    }

    // 处理翻译请求
    async function handleTranslate() {
        try {
            // 显示加载状态
            translateBtn.disabled = true;
            translateBtnText.innerHTML = '<span class="loading"></span>翻译中...';

            // 获取当前标签页
            const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

            if (!tab) {
                throw new Error('无法获取当前标签页');
            }

            // 发送翻译请求到content script
            await chrome.tabs.sendMessage(tab.id, {
                action: 'translate',
                source: 'popup'
            });

            // 关闭popup
            window.close();

        } catch (error) {
            console.error('Translation error:', error);
            translateBtnText.textContent = '翻译失败';
            setTimeout(() => {
                translateBtn.disabled = false;
                translateBtnText.textContent = '翻译当前页面';
            }, 2000);
        }
    }

    // 打开设置页面
    function openSettings() {
        chrome.runtime.openOptionsPage();
    }

    // 处理消息
    function handleMessage(request, sender, sendResponse) {
        if (request.action === 'translationComplete') {
            // 翻译完成，可以更新UI状态
            console.log('Translation completed');
        } else if (request.action === 'translationError') {
            // 翻译错误
            console.error('Translation error:', request.error);
        }
    }
});